import { getMenus } from '@/api/role'
import { constantRoutes, mainRoutes, _import } from '@/router'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.Children) {
        tmp.Children = filterAsyncRoutes(tmp.Children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  router: {},
  mainRoutes: {}
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROUTER: (state, router) => {
    state.router = router
  },
  SET_MAINROUTES: (state, routes) => {
    state.mainRoutes = routes
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    const routes = []
    return new Promise(resolve => {
      getMenus(roles).then(response => {
        const data = response.data
        if (data && data.length > 0) {
          fnAddDynamicMenuRoutes(data, state.router, routes)
          state.routes = data
          const accessedRoutes = sessionStorage.getItem('dynamicMenuRoutes')
          resolve(accessedRoutes)
        }
      })
    })
  }
}

function fnAddDynamicMenuRoutes(menuList, router, routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].Children && menuList[i].Children.length >= 1) {
      temp = temp.concat(menuList[i].Children)
    } else if (menuList[i].Url && /\S/.test(menuList[i].Url)) {
      menuList[i].Url = menuList[i].Url.replace(/^\//, '')
      var route = {
        path: menuList[i].Url.replace('/', '-'),
        component: null,
        name: menuList[i].Url.replace('/', '-'),
        meta: {
          menuId: menuList[i].Id,
          title: menuList[i].Name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      route['component'] = _import(`modules/${menuList[i].Url}/index`) || null
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, router, routes)
  } else {
    state.mainRoutes.name = 'main-dynamic'
    state.mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: { name: '404' }}
    ])
    console.log(routes)
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
